package server.controller;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.FrmDictionDao;
import server.model.entity.FrmDiction;
import server.tool.tool.TimeUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("v1/img")
@Api
public class ImgController {
    @Value("${folderPath}")
    private String folderPath;
    @Value("${folderType}")
    private String folderType;
    @Value("${host-main}")
    private String hostMain;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private FrmDictionDao dictionarysDao;
    @Autowired
    private HttpServletResponse response;

    @Value("${imgHref}")
    private String href;

    @Value("${host}")
    String host;

    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation("上传图片，需要在url后拼接一个随机字符串project=xxxx")
    @CrossOrigin(origins = "*")
    public RetResult photoUpload(MultipartFile file, String project) throws Exception {
        Map<String, Object> res = new LinkedHashMap<String, Object>();
        String data = null;
        try {
            if (!file.isEmpty()) {
                try {
                    BASE64Encoder encoder = new BASE64Encoder();
                    // 通过base64来转化图片
                    data = encoder.encode(file.getBytes());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            String req = project;
            if (StringUtils.isEmpty(req)) {
                req = TimeUtils.getTimeStmp();
            }
            FrmDiction diction = dictionarysDao.findByKeyst(req);
            if (diction != null) {
                return RetResponse.makeErrRsp("error");
            }
            diction = new FrmDiction();
            diction.setVal(data);
            diction.setKeyst(req);
            dictionarysDao.save(diction);
            res.put("code", "0");
            res.put("msg", "成功");
            Map<String, String> das = new LinkedHashMap<String, String>();
            das.put("src", "/v1/img/getImg?project=" + req);
            res.put("data", das);
        } catch (Exception e) {
            res.put("code", "1");
            res.put("msg", "失败");
        }
        response.setHeader("Access-control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,token");
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        return RetResponse.makeOKRsp(res);
    }

    @GetMapping("/getImg")
    @ResponseBody
    @ApiOperation("访问图片，在url带参数project=xxx")
    @CrossOrigin(origins = "*")
    public void GetImg(HttpServletResponse rp, String project) throws IOException {
        FrmDiction diction = dictionarysDao.findByKeyst(project);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] decodeBuffer = decoder.decodeBuffer(diction.getVal());
        String rdm = UUID.randomUUID().toString();
        FileUtil.touch(href + "/" + rdm + ".jpg");
        OutputStream out = new FileOutputStream(href + "/" + rdm + ".jpg");
        out.write(decodeBuffer);
        out.flush();
        out.close();
        String filePath = href + "/" + rdm + ".jpg";
        File imageFile = new File(filePath);
        if (imageFile.exists()) {
            FileInputStream fis = null;
            OutputStream os = null;
            try {
                fis = new FileInputStream(imageFile);
                os = rp.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("uploadsWang")
    @ResponseBody
    public RetResult uploadsWang(@RequestParam(value = "myFileName") MultipartFile mf) {
        String realPath = folderPath;
        try {
            if (!StringUtils.isEmpty(mf) && mf.getSize() > 0) {
                String filename = mf.getOriginalFilename();
                String[] names = filename.split("\\.");//
                String tempNum = (int) (Math.random() * 100000) + "";
                if (!folderType.contains(names[1].toUpperCase())) {
                    return RetResponse.makeErrRsp("非法的文件！");
                }
                String uploadFileName = tempNum + System.currentTimeMillis() + "." + names[names.length - 1];
                File targetFile = new File(realPath, uploadFileName);
                mf.transferTo(targetFile);
                return RetResponse.makeOKRsp(hostMain + "/v1/img/file/" + uploadFileName);
            }
        } catch (Exception e) {
            return RetResponse.makeErrRsp("上传失败");
        }
        return RetResponse.makeErrRsp("上传失败");
    }

    @RequestMapping("file/{time}")
    @ResponseBody
    public void getFiles(@PathVariable("time") String time) {
        String path = "/" + time;
        File imageFile = new File(folderPath + path);
        if (imageFile.exists()) {
            FileInputStream fis = null;
            OutputStream os = null;
            try {
                fis = new FileInputStream(imageFile);
                os = response.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("file/{projectId}/{date}/{time}")
    @ResponseBody
    public void getFile(@PathVariable("projectId") String projectId, @PathVariable("date") String date, @PathVariable("time") String time) {
        String path = "/" + projectId + "/" + date + "/" + time;
        File imageFile = new File(folderPath + path);
        if (imageFile.exists()) {
            FileInputStream fis = null;
            OutputStream os = null;
            try {
                fis = new FileInputStream(imageFile);
                os = response.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
